
const path = require('path');
const fs = require('fs');
const utils = require('../common/utils');
const toolConfig = require('../pack_exe/toolConfig');
const exceljs = require('../npm/node_modules/exceljs')


var excel_export = {

    _srcDir: "",
    _exportDir: "",
    _cvsDir: "",

    _allFiles: [],

    async start() {
        let [excelPath, exportExcel, excel_csv] = toolConfig.getExcelPath()
        this._srcDir = excelPath
        this._exportDir = exportExcel
        this._cvsDir = excel_csv
        try {
            await this.initAllFiles()
        } catch (error) {
            console.log(`\n\n\t${error}\n\n`)
        }
        return true
    },

    async initAllFiles() {
        this._allFiles = []
        let files = utils.walkDirFiles(this._srcDir)
        for (let i = 0; i < files.length; i++) {
            await this.analysisFiles(files[i])
        }

        this.export_csv_files()
        this.export_json_data()
    },

    // 初始化所有excel数据信息
    async analysisFiles(filename) {

        let parse = path.parse(filename)
        if (parse.ext != ".xlsx") return
        if (parse.name.startsWith(`~$`)) return
        let nameSplit = parse.name.split("_")
        if (nameSplit.length < 3) {
            throw new Error(`配置表表名命名不规范[parse.name]  正确格式[字母序号(英文)_说明(中文)_表名(英文)]]`)
        }
        let excelDecript = nameSplit[1]
        nameSplit.splice(0, 2)
        let className = nameSplit.join("_")

        let workBook = new exceljs.Workbook()
        let workBookData = await workBook.xlsx.readFile(filename)
        let sheetData = workBookData.worksheets[0]

        // 第一行数据是字段名 遇到空列停止遍历
        let headerIndex = []
        let headerList = []
        let headerRow = sheetData.findRow(1).values
        let headerStart = false
        for (let i = 0; i < headerRow.length; i++) {
            if (headerRow[i]) {
                headerStart = true
                headerIndex.push(i)
                headerList.push(headerRow[i])
            } else if (headerStart) {
                break
            }
        }
        // 第二行数据是字段描述
        let descriptRow = sheetData.findRow(2).values
        let descriptList = []
        for (let i = 0; i < headerIndex.length; i++) {
            descriptList.push(descriptRow[headerIndex[i]])
        }
        // 第三行数据是字段类型
        let dataTypeRow = sheetData.findRow(3).values
        let dataTypeList = []
        for (let i = 0; i < headerIndex.length; i++) {
            let paramType = dataTypeRow[headerIndex[i]]
            for (let j = 1; j <= 2; j++) {
                paramType = paramType.replaceAll(`##${j}`, "")
            }
            dataTypeList.push(paramType)
        }

        // 数据内容 从第四行开始 遇到空行停止遍历
        let datas = []
        let rowCount = sheetData.rowCount
        for (let i = 4; i <= rowCount; i++) {
            let rowData = sheetData.findRow(i).values
            let data = []
            let isBreak = false
            for (let j = 0; j < headerIndex.length; j++) {
                if (!rowData[headerIndex[j]] && j == 0) {
                    isBreak = true
                    break
                }
                let cellData = ""
                if (typeof rowData[headerIndex[j]] == 'object') {
                    cellData = rowData[headerIndex[j]].result + ""
                } else {
                    cellData = rowData[headerIndex[j]] ? (rowData[headerIndex[j]] + "") : ""
                }
                cellData = cellData.replace(/\s+/g, '')
                if (cellData.length <= 0) {
                    throw new Error(`数据为空:  配置表[${parse.name}]  行号:[${i}]  列号:[${headerIndex[j]}]`)
                }
                data.push(cellData)
            }
            if (isBreak) break

            datas.push(data)
        }

        let analysisData = {
            headerList: headerList,
            descriptList: descriptList,
            dataTypeList: dataTypeList,
            datas: datas,
            className: className,
            excelDecript: excelDecript
        }

        this._allFiles.push(analysisData)

        // // 写入json文件        
        // let content = "{"
        // content = `${content}\n\t"header":${JSON.stringify(headerList)}`
        // content = `${content},\n\t"datas":\n\t[`
        // for(let i = 0; i < datas.length; i++){
        //     content = `${content}${i == 0?"":","}\n\t\t${JSON.stringify(datas[i])}`
        // }
        // content = `${content}\n\t]`
        // content = `${content}\n}`
        // fs.writeFileSync(exportFileName,content)    
        // console.log(`配置表导出完成:${parse.name}\n`)    
    },

    export_csv_files() {

        let excelMgrClassContent = `import { BaseCsv } from "./BaseCsv"\n`
        let excelMgrConten = "\nexport class csv{"
        let allFilesStr = []
        let loadConfig = "\n\tpublic static loadConfig<T>(name: string, asset: T) {"
        loadConfig = `${loadConfig}\n\t\tswitch (name) {`
        for (let i = 0; i < this._allFiles.length; i++) {
            let fileData = this._allFiles[i]
            excelMgrClassContent = `${excelMgrClassContent}${this.export_class(fileData)}`
            excelMgrConten = `${excelMgrConten}${this.export_static_func(fileData.className)}`

            allFilesStr.push(fileData.className)

            loadConfig = `${loadConfig}\n\t\t\tcase "${fileData.className}":BaseCsv.loadData<${fileData.className},T>(name,asset, ${fileData.className}); break;`
        }
        loadConfig = `${loadConfig}\n\t\t}`
        loadConfig = `${loadConfig}\n\t}`

        allFilesStr = `\n\tpublic static readonly allFiles = ${JSON.stringify(allFilesStr)}`
        excelMgrConten = excelMgrConten + loadConfig + allFilesStr + "\n}"
        let content = `${excelMgrClassContent}${excelMgrConten}`
        fs.writeFileSync(path.join(this._cvsDir, "csv.ts"), content)
    },

    export_class(fileData) {
        let headerList = fileData.headerList
        let descriptList = fileData.descriptList
        let dataTypeList = fileData.dataTypeList
        let className = fileData.className

        // public readonly typeStr = {ItemID: "number",name: "string",icon: "string",pointPosition: "string",time:"number"}
        let typeStr = []
        for (let i = 0; i < headerList.length; i++) {
            typeStr.push(`${headerList[i]}:"${dataTypeList[i]}"`)
        }
        let retStr = ""
        retStr = `\nexport class ${className} extends BaseCsv{`
        retStr = retStr + `\n\tpublic readonly typeStr = {${typeStr.join(",")}}`
        retStr = retStr + `\n\tpublic static readonly excelname = "${className}"`
        for (let i = 0; i < headerList.length; i++) {
            retStr = `${retStr}${this.export_param(headerList[i], dataTypeList[i], descriptList[i])}`
        }
        retStr = `${retStr}\n}`
        return retStr
    },

    export_param(name, type, descript) {
        let retStr = ""
        retStr = `\n\t/**\n\t* ${descript}\n\t*/\n\tpublic ${name}:${type}`
        return retStr
    },

    export_static_func(className) {
        let retStr = ""
        retStr = `\n\tpublic static ${className}(id:number):${className}{`
        retStr = `${retStr}\n\t\treturn BaseCsv.getData<${className}>(${className}.excelname,id)`
        retStr = `${retStr}\n\t}`
        retStr = `${retStr}\n\tpublic static get ${className}_all():Map<number, ${className}>{`
        retStr = `${retStr}\n\t\treturn BaseCsv.getAllData<${className}>(${className}.excelname)`
        retStr = `${retStr}\n\t}`
        return retStr
    },

    export_json_data() {

        for (let i = 0; i < this._allFiles.length; i++) {
            let fileData = this._allFiles[i]
            let content = "{"
            content = `${content}\n\t"header":${JSON.stringify(fileData.headerList)}`
            content = `${content},\n\t"rows":{`
            for (let i = 0; i < fileData.datas.length; i++) {
                content = `${content}${i == 0 ? "" : ","}\n\t\t"${fileData.datas[i][0]}":${JSON.stringify(fileData.datas[i])}`
            }
            content = `${content}\n\t}`
            content = `${content}\n}`

            let exportFileName = path.join(this._exportDir, fileData.className + ".json")
            fs.writeFileSync(exportFileName, content)
            console.log(`\t\t配置表导出完成:${fileData.className}`)
        }


        // // 写入json文件        

    },






}
module.exports = excel_export;